package com.dimld.connect.websocket;

import com.dimld.connect.MsgReaderI;
import io.undertow.websockets.WebSocketConnectionCallback;
import io.undertow.websockets.core.WebSocketChannel;
import io.undertow.websockets.spi.WebSocketHttpExchange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

public class WebSocketHandler implements WebSocketConnectionCallback {

    private final Logger   wsLog = LoggerFactory.getLogger("ws");
    private final Class<?> wsReaderClass;
    private final int      timeout;
    private final String   serviceUUID;

    public WebSocketHandler(Class<?> wsReaderClass, int timeout, String serviceUUID) {
        this.wsReaderClass = wsReaderClass;
        this.timeout = timeout;
        this.serviceUUID = serviceUUID;
    }

    @Override
    public void onConnect(WebSocketHttpExchange webSocketHttpExchange, WebSocketChannel webSocketChannel) {
        String s = webSocketChannel.getSourceAddress().toString().replace("/", "");
        wsLog.info("[WEBSOCKET][{}]客户端连接", s);
        String uuid = UUID.randomUUID().toString();
        if (wsReaderClass != null) {
            try {
                MsgReaderI reader = (MsgReaderI) wsReaderClass.newInstance();
                webSocketChannel.getReceiveSetter().set(new WebSocketClientHandler(webSocketChannel, uuid, reader, timeout, serviceUUID));
                webSocketChannel.resumeReceives();
            } catch (Exception e) {
                wsLog.error("异常", e);
            }
        }
    }
}